<template>
	<view class="container">
		<view class="button-group">
			<u-button text="返回首页" color="#F57B00" plain shape="circle" @click="saveAudio"></u-button>
			<u-button text="保存音频" color="#F57B00" shape="circle" @click="saveAudio"></u-button>
		</view>
		<view class="page-body">
			<view class="page-section page-section-gap" style="text-align: center;">
				<audio style="text-align: left" :src="videoList.resUrl" :poster="video.pic" :name="video.title"
					:author="video.resName" controls></audio>
			</view>
		</view>


	</view>
</template>

<script>
	export default {
		data() {
			return {
				videoList: {},
				video: {},
				audioDuration: 0, // 音频时长
				innerAudioContext: null, // 音频上下文对象
			}
		},
		onShow() {
			this.videoList = uni.getStorageSync('videolist')
			this.video = uni.getStorageSync('video')
			this.getAudioDuration()

		},
		methods: {
			getAudioDuration() {
				// 创建音频上下文
				this.innerAudioContext = uni.createInnerAudioContext();

				// 设置音频文件路径
				this.innerAudioContext.src = this.videoList.resUrl;

				// 监听音频可以播放的事件
				this.innerAudioContext.onCanplay(() => {
					// 使用定时器延迟获取音频时长
					let intervalID = setInterval(() => {
						if (this.innerAudioContext.duration !== 0) {
							clearInterval(intervalID); // 清除定时器
							const duration = this.innerAudioContext.duration / 60
							this.audioDuration = duration.toFixed(2); // 保留两位小数
							console.log('音频时长：', this.audioDuration);
						}
					}, 500);
				});

				// 监听错误事件
				this.innerAudioContext.onError((err) => {
					console.error('音频加载失败：', err);
				});

				// 触发一次播放事件，以便能够获取到音频时长
				this.innerAudioContext.play();
				this.innerAudioContext.pause(); // 可以立即暂停，不影响获取到音频时长
			},

			saveAudio() {
				uni.saveFile({
					tempFilePath: this.innerAudioContext.src,
					success: (res) => {
						console.log('保存成功', res.savedFilePath);
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
					},
					fail: (err) => {
						console.error('保存失败', err);
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					}
				});
			}
		},
		beforeDestroy() {
			// 销毁音频上下文
			if (this.innerAudioContext) {
				this.innerAudioContext.destroy();
			}
		},


	}
</script>

<style>
	.container{
		padding: 20rpx;
	}
	audio {
		width: 100%;
		height: 300rpx;
	}

	.button-group {
		display: flex;
		justify-content: space-between;
		margin: 50rpx;
		gap: 40rpx;

		.u-button--plain {
			background: #fde4cb;
		}

		button {
			flex: 1;
			height: 80rpx;
			line-height: 80rpx;
			font-weight: 400;
			font-family: PingFangSC, PingFang SC;
			font-size: 28rpx !important;
			border: none !important;
		}


	}
</style>